import storage from '../../utils/storage';
import utils from '../../utils';
import { EnumDef } from '../../lib/enum-def';

export default {
  namespaced: true,
  state: () => ({
    enums: {},
    loaded: false,
  }),
  getters: {
    getEnums,
    isLoaded: state => state.loaded,
  },
  mutations: {
    setEnums: (state, enums) => {
      state.enums = enums;
      state.loaded = true;
      storage.set('enums', enums)
    },
    clearEnums: (state) => {
      state.enums = {}
      state.loaded = false
      state.lastUpdated = null
      storage.remove('enums');
    }
  },
};

function getEnums(state) {
  return enumName => {
    const enumsData = utils.replaceInvalidValue(state.enums,
      storage.get('enums') || {})
    const enumDefs = {};
    Object.entries(enumsData).forEach(([key, values], index) => {
      try {
        enumDefs[key] = EnumDef.fromJSON(values);
      } catch (error) {
        console.error(`解析枚举 ${key} 失败:`, error);
      }
    });

    return enumDefs[enumName] || null;
  }
}